package cn.tom.tompicturebackend.api.imagesearch.sub;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.tom.tompicturebackend.api.imagesearch.model.ImageSearchResult;
import cn.tom.tompicturebackend.exception.BusinessException;
import cn.tom.tompicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class GetImageListApi {

    public static List<ImageSearchResult> getImageList(String url){
        try{
            //发起GET请求
            HttpResponse response = HttpUtil.createGet(url).execute();
            int statusCode = response.getStatus();
            String body = response.body();

            if (statusCode == 200){
                return processResponse(body);
            }else{
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }catch (Exception exception){
            log.error("获取图片列表失败",exception);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }private static List<ImageSearchResult> processResponse(String responseBody) {
        // 解析响应体，返回图片列表
        JSONObject jsonObject = new JSONObject(responseBody);
        if(!jsonObject.containsKey("data")){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if(!data.containsKey("list")){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        JSONArray list = data.getJSONArray("list");
        return JSONUtil.toList(list,ImageSearchResult.class);
    }



}
